package pw.hais.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * 基础控制器
 * @author Hello_海生
 * @date 2014年7月23日
 */
@WebServlet(name = "Base")
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String msg="msg";			//返回提示语句
	public static final String data="data";			//返回 数据
	public static final String code="code";			//返回的 code
	
	public Map<String,Object> val = null;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private PrintWriter out = null;

    protected BaseServlet() {
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		//获取赋值
		val = new HashMap<String,Object>();
		this.request = req;
		this.response = resp;
		//设置输出的编码
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		this.out =  resp.getWriter();
	}
	
	/**
	 * 显示JSON 到 界面
	 * @param map	需要转换为 json 的  MAP
	 */
	public void printJSON(Map<String,Object> map){
		try {
			String json = JSON.toJSON(map).toString();
			System.out.println("--返回请求结果："+json);
			out.println(json);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	/**
	 * 获取 字符串 类型 参数
	 * @param str
	 * @return
	 */
	public String getString(String str){
		String value = request.getParameter(str);
		if(value==null)value="";
		return value;
	}
	
	/**
	 * 获取 整数 类型 参数
	 * @param str
	 * @return
	 */
	public int getInt(String str){
		int value = 0;
		try {
			value = Integer.parseInt(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
	
	/**
	 * 获取 长整 类型 参数
	 * @param str
	 * @return
	 */
	public long getlong(String str){
		long value = 0;
		try {
			value = Long.valueOf(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
	
	/**
	 * 获取 浮点型  类型 参数
	 * @param str 
	 * @return
	 */
	public float getFloat(String str){
		float value = 0;
		try {
			value = Float.valueOf(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
	

}
